<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Objects in Ruby</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Ruby, objects, tutorial, programming language, learn Ruby">
<meta name="description" content="In this part of the Ruby tutorial, we cover Ruby objects.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container2">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<div class="content2">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>



<h1>Objects in Ruby</h1>

<p>
In this part of the Ruby tutorial, we will briefly cover the concept of
objects in Ruby language. We will learn more about objects in OOP chapter. 
I have decided to write this preliminary chapter about objects, because
many Ruby features might be confusing to newcomers. Especially if they already
know any other programming language. 
</p>

<div class="big_hor">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* big_horizontal */
google_ad_slot = "2904953388";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<p>
Ruby is an object-oriented programming language. This means, than in Ruby
programs we work with objects. From a language programmer's point of view a
Ruby program is a stream of tokens. These tokens are Ruby keywords, operators,
various delimiters or literals. From a semantic point of view a Ruby program
consists of objects. These objects are created and modified during the lifetime
of a Ruby script. 
</p>

<p>
There are two kinds of objects. Built-in objects and custom objects. Built-in
objects are predefined objects that all programmers can use. They are available 
with the core of the Ruby language or from various libraries. Custom objects are
created by application programmers for their application domains. 
</p>

<p>
All objects must be created, before we can work with them. We often use a term
object instantiation. It is a synonym for object creation. Objects consists of two
basic things. Data and methods. Data is a static part of an object. Methods form 
a dynamic part of an object. Objects are modified and communicate with each other
via methods.
</p>

<pre class="code">
#!/usr/bin/ruby

puts "Ruby language"
</pre>

<p>
We have a simple Ruby script. If we are familiar with some procedural language, like
Pascal or C, we might see a keyword or a function named <code>puts</code> and its
parameter "Ruby language", which is a string. 
</p>

<p>
Ruby is a pure object-oriented langauge and things are a bit different. The "Ruby language"
is a indeed a string, which is a common data type. But it is also an object. And as with
all objects, we can call its methods. This is a bit different from other languages. For example,
this would not be possible in Python programming language. The <code>puts</code> is a method. 
A method is a function defined in an object. Methods do not exist on their own. In fact, the
<code>puts</code> method is a part of the <code>Kernel</code> module. 
</p>

<pre class="code">
#!/usr/bin/ruby

Kernel.puts "Ruby language"
Kernel.puts "Ruby language".size
</pre>

<p>
In the above script, we have two code lines. 
</p>

<pre class="explanation">
Kernel.puts "Ruby language"
</pre>

<p>
In the first example, we were calling the <code>puts</code> method without the <code>Kernel</code>
part, which may be omitted. This saves time and some typing. It is in fact a shorthand call for the
<code>Kernel.puts</code> formal call. In C# we have <code>Console.writeln</code> and in Java
<code>System.println</code>. The idea is the same. Methods must be associated with some object. Or
a class, in case of class methods. But in the case of Java and C# the first parts, 
the Console and the System may not be omitted. 
</p>

<pre class="explanation">
Kernel.puts "Ruby language".size
</pre>

<p>
In this code line, we print the size of the "Ruby language" string to the console. This might
be confusing to many programmers, that come from other languages. In other languages, a string
is a primitive data type and cannot be modified. And does not have its own methods. In Ruby, a
string is a full object and has its own methods. The <code>size</code> method is one of them. 
It returns the size of the string in characters. 
</p>

<pre>
$ ./simple2.rb
Ruby language
13
</pre>

<p>
Output of the code example. 
</p>

<hr class="btm">

<p>
In the following example, we will look at an integer number.
Similarly to a string, an integer value is a Ruby object too.
</p>

<pre class="code">
#!/usr/bin/ruby

puts 6.object_id

puts 6.even?
puts 6.zero?

puts 6.class
</pre>

<p>
In the example, we have an integer 6. We call a few methods
on the number. 
</p>

<pre class="explanation">
puts 6.object_id
</pre>

<p>
The 6 is an object. The <code>object_id</code> is a method. The method
returns an id associated to the object. Each object has an id. If
we call a method on an object, we must always put a dot character between
the two. 
</p>

<pre class="explanation">
puts 6.even?
puts 6.zero?
</pre>

<p>
Here we call two methods on the 6 object. The <code>even?</code> returns true
if the number is even. And the <code>zero?</code> method returns true, if the
number is equal to zero. Note that these two methods end with a question mark.
This is a Ruby convention. Methods that return a boolean value end
with a question mark. 
</p>

<pre class="explanation">
puts 6.class
</pre>

<p>
The <code>class</code> method tells us what kind of object we are dealing with. 
In our case a 6 is a <code>Fixnum</code>
</p>

<pre>
$ ./objectnumber.rb
13
true
false
Fixnum
</pre>

<p>
Code example output. 
</p>


<h2>Object creation</h2>

<p>
We have mentioned, that Ruby objects must be created before we can work with
them. Objects can be created implicitly or explicitly. Implicit object creation
is object creation by literal notation. Explicit object creation happens with
the use of the <code>new</code> keyword. A custom object is always
created with the <code>new</code> keyword. Custom objects must be created from
a particular class. A class is a template for an object. 
A class can be used to create many objects. 
</p>


<pre class="code">
#!/usr/bin/ruby

class Being
end
    
puts 67
puts "ZetCode"

s = String.new "ZetCode"
puts s

# n1 = Fixnum.new 67
# puts n1

b = Being.new
puts b
</pre>

<p>
The code example demonstrates creation of objects in Ruby. 
</p>

<pre class="explanation">
class Being
end
</pre>

<p>
This is a template for our custom object called Being. The
templates are created using the <code>class</code> keyword. 
The templates for custom objects are usually placed at the 
top of the source file or in a separate Ruby files. 
</p>

<pre class="explanation">
puts 67
puts "ZetCode"
</pre>

<p>
In these two lines we work with two objects. A 67 object of <code>Fixnum</code>
type and "ZetCode" string of <code>String</code> type. 67 and "String" are what
we call literals. A literal is a textual representation of a particular value 
of a type. These two objects are created behind the scenes by the Ruby interpreter. 
Some objects in Ruby are created by specifying their literals in the source code.
</p>

<pre class="explanation">
s = String.new "ZetCode"
puts s
</pre>

<p>
This is the formal way of creating a <code>String</code> object. It is equal to the
previous, implicit creation with the string literal. 
</p>

<pre class="explanation">
# n1 = Fixnum.new 67
# puts n1
</pre>

<p>
Not all built-in objects can be created with the <code>new</code> method. This code
does not compile. Fixnum numbers can be created only by the literal notation so far. 
</p>

<pre class="explanation">
b = Being.new
puts b
</pre>

<p>
And here we create an instance of the custom object. The <code>puts</code> method
gives us a short description of the object. 
</p>

<pre>
$ ./ocreation.rb
67
ZetCode
ZetCode
#&lt;Being:0x9944d9c&gt;
</pre>

<p>
Output of the example.
</p>


<hr class="btm">

<p>
We will continue with some formal object creations.
</p>

<pre class="code">
#!/usr/bin/ruby

s1 = String.new "Ruby"
puts s1.size
puts s1.downcase

a1 = Array.new 
a1.push 1, 2, 3
puts a1.include? 3
puts a1.empty?

r1 = Range.new 1, 6
puts r1.class
puts r1.include? 4
</pre>

<p>
In the example, we create three built-in objects and
call a few of their methods. 
</p>

<pre class="explanation">
s1 = String.new "Ruby"
puts s1.size
puts s1.downcase
</pre>

<p>
A <code>String</code> object is created. We call two methods of the
object. The <code>size</code> method returns the size of the string. 
The <code>downcase</code> method downcases the characters of the string.
</p>

<pre class="explanation">
a1 = Array.new 
a1.push 1, 2, 3
puts a1.include? 3
puts a1.empty?
</pre>

<p>
Here we create an <code>Array</code> object and add three numbers to it.
Later we call two array methods. The <code>include?</code> method checks if
a particular value (3 in our case) is part of the array. The <code>empty?</code>
method returns a boolean value indicating, whether the array is empty or not.
</p>

<pre class="explanation">
r1 = Range.new 1, 6
puts r1.class
puts r1.include? 4
</pre>

<p>
An instance of the <code>Range</code> class is created. It contains numbers from 1
to 6. The <code>class</code> method returns the name of the object. 
The <code>include?</code> method checks if the number 4 is part of 
the range. It is in our case. 
</p>

<pre>
$ ./formal.rb
4
ruby
true
false
Range
true
</pre>

<p>
Running the example gives this output. 
</p>


<h2>Object literals</h2>

<p>
As we have already mentioned, some built-in objects can be created
using object literals. The following example shows several object literals.
</p>

<pre class="code">
#!/usr/bin/ruby

4.times { puts "Ruby" }

puts "Ruby".size
puts "Ruby".downcase

puts [1, 2, 3].include? 3
puts [1, 2, 3].empty?

puts :name.class
puts :name.frozen?

puts (1..6).class
puts (1..6).include? 4
</pre>

<p>
In the above example we use literal notation to create a Fixnum,
Strings, Arrays, Symbols and Ranges. 
</p>

<pre class="explanation">
4.times { puts "Ruby" }
</pre>

<p>
We can immediately call a method on an integer literal. This line
prints a "Ruby" string four times to the terminal. 
</p>

<pre class="explanation">
puts "Ruby".size
puts "Ruby".downcase
</pre>

<p>
We call two methods on a String object created with a string
literal. 
</p>

<pre class="explanation">
puts [1, 2, 3].include? 3
puts [1, 2, 3].empty?
</pre>

<p>
Here we create two Array objects using array literal notations.
We check if a specific number is part of the array with the 
<code>include?</code> method. The <code>empty?</code> method checks
if the array object is empty or not. 
</p>

<pre class="explanation">
puts :name.class
puts :name.frozen?
</pre>

<p>
Two methods of the Symbol object are called. The symbol is created
with a symbol literal, which starts with a colon.
</p>

<pre class="explanation">
puts (1..6).class
puts (1..6).include? 4
</pre>

<p>
Two Range objects are created using the range literal. We call two 
methods on those objects. The <code>class</code> method returns
the name of the class and the <code>include?</code> method checks
if a given number is part of the range. 
</p>

<pre>
$ ./literals.rb
Ruby
Ruby
Ruby
Ruby
4
ruby
true
false
Symbol
false
Range
true
</pre>

<p>
Example output.
</p>


<h2>Object hierarchy</h2>

<p>
In object-oriented languages objects form a hierarchy. Ruby is no
exception. It is a tree-like hierarchy, where we have
parent objects and child objects. Objects inherit data and behaviour
from their parent objects. At the top of the hierarchy there is the
root object. It is called the <code>Object</code>. Each object in Ruby
has at least one parent. In other words, every object inherits from 
the basic <code>Object</code> object. 
</p>

<p>
According to the official Ruby documentation, <code>Object</code> is the root of 
Ruby's class hierarchy. Its methods are available to all classes 
unless explicitly overridden.
</p>

<pre class="code">
#!/usr/bin/ruby

puts 4.is_a? Object
puts "Ruby".is_a? Object
puts [2, 3].is_a? Object
puts :name.is_a? Object
puts (1..2).is_a? Object
</pre>

<p>
In the above code example we demonstrate, that all objects inherit 
from the root <code>Object</code>
</p>

<pre class="explanation">
puts 4.is_a? Object
</pre>

<p>
We use the <code>is_a?</code> method to check, if the
number is a specific type. In other words, if it inherits from
a given object type. 
</p>


<pre>
$ ./mother.rb 
true
true
true
true
true
</pre>

<p>
All methods return true, which means that all objects inherit from the
mother object. 
</p>

<hr class="btm">

<p>
The inheritance hierarchy may be quite complex even
for the very basic Ruby objects. 
</p>

<pre class="code">
#!/usr/bin/ruby

puts 6.class

puts 6.is_a? BasicObject
puts 6.is_a? Object
puts 6.is_a? Numeric
puts 6.is_a? Integer
puts 6.is_a? Fixnum

puts 6.is_a? Bignum
puts 6.is_a? String
</pre>

<p>
In this example we shed some light on the inheritance hierarchy
of a small numerical value.
</p>


<pre class="explanation">
puts 6.class
</pre>

<p>
We find out what kind of object is the number value 6. 
The line prints <code>Fixnum</code> to the console. 
</p>

<pre class="explanation">
puts 6.is_a? BasicObject
puts 6.is_a? Object
puts 6.is_a? Numeric
puts 6.is_a? Integer
puts 6.is_a? Fixnum
</pre>

<p>
All the above lines return true. 
Number 6 is a <code>Fixnum</code>. From the Ruby documentation
we find out that the four other objects are parents of the <code>Fixnum</code>
object. 
</p>

<pre class="explanation">
puts 6.is_a? Bignum
puts 6.is_a? String
</pre>

<p>
The above two objects are not parents for the 6 value. 
</p>

<pre>
$ ./inheritance.rb
Fixnum
true
true
true
true
true
false
false
</pre>

<p>
Output of the example. 
</p>

<hr class="btm">

<p>
We will finish this section with an example, demonstrating
inheritance of custom user objects. 
</p>

<pre class="code">
#!/usr/bin/ruby

class Being

    def to_s
        "This is Being"
    end
    
    def get_id
        9
    end
end

class Living &lt; Being
    
    def to_s
        "This is Living"
    end
end

l = Living.new

puts l
puts l.get_id
puts l.is_a? Being
puts l.is_a? Object
puts l.is_a? BasicObject
</pre>

<p>
In the example we create two objects. Being and Living. The Living
object inherits from the Being. The first is a parent object and the second
is a child object. 
</p>


<pre class="explanation">
class Being

    def to_s
        "This is Being"
    end
    
    def get_id
        9
    end
end
</pre>

<p>
This is a definition of a custom Ruby object. The definition is placed
between the <code>class</code> and <code>end</code> keywords. Inside the
definition, we create two methods. When the <code>puts</code> method
takes an object as a parameter, it calls its <code>to_s</code> method.
It usually gives a string representation/description of the object. 
</p>

<pre class="explanation">
class Living &lt; Being
    
    def to_s
        "This is Living"
    end
end
</pre>

<p>
We create a definition of the <code>Living</code> object. The object
inherits from the <code>Being</code> object. The &lt; operator is used
to create inheritance relationships. The  <code>to_s</code> method is
overwritten. 
</p>

<pre class="explanation">
l = Living.new
</pre>

<p>
From the above Living object template, we create an instance 
of the Living object. The instance of a custom object is created with 
the <code>new</code> keyword. 
</p>

<pre class="explanation">
puts l
</pre>

<p>
The <code>puts</code> method calls the <code>to_s</code> method of
the Living object. Had the <code>to_s</code> method not been defined
in the Living class, the <code>to_s</code> method of the Being
class would have been called. 
</p>

<pre class="explanation">
puts l.get_id
</pre>

<p>
The Living object has no get_id method defined. In such a case, the
parent classes are checked, if there is such a method. In our case
the Being method has such a method and it is called. 
</p>

<pre class="explanation">
puts l.is_a? Being
</pre>

<p>
The line returns true. The Living is a type of a Being; e.g. it inherits
from the Being class. 
</p>

<pre class="explanation">
puts l.is_a? Object
puts l.is_a? BasicObject
</pre>

<p>
For our Living custom object, we have not explicitly specified
any relation to the <code>Object</code> or <code>BasicObject</code> 
objects. Yet the two lines return true. This is because every object
in Ruby is automatically a descendant of these two objects. This is
done behind the scenes by the Ruby interpreter.
</p>

<pre>
$ ./custominher.rb
This is Living
9
true
true
true
</pre>

<p>
Output of the example. 
</p>


<h2>Ruby toplevel</h2>

<p>
Ruby has a specific object reffered to as Ruby toplevel. It is a default execution
environment defined outside any other context like class or module definition.
The toplevel's name is <b>main</b>. It is an instance of the <code>Object</code> type.
There is a local space associated with the main, where all local variables reside. 
</p>

<pre class="code">
#!/usr/bin/ruby

n1 = 3
n2 = 5

puts local_variables

Kernel.puts self
puts self.class
</pre>

<p>
This is the first example describing the Ruby toplevel.
</p>

<pre class="explanation">
n1 = 3
n2 = 5
</pre>

<p>
Here we have defined two numeric variables. These variables are local to
the toplevel. 
</p>

<pre class="explanation">
puts local_variables
</pre>

<p>
Here we produce a list of all local variables. The <code>local_variables</code>
is a method of the <code>Kernel</code> module, which is mixed into 
each <code>Object</code>, including the toplevel object. 
</p>

<pre class="explanation">
Kernel.puts self
</pre>

<p>
The <code>self</code> is a Ruby pseudo variable. It returns the current object 
receiver. The line prints "main" to the console. It is the name for the Ruby
toplevel. The <code>Kernel</code> part of the <code>Kernel.puts</code> code
can be omitted. By fully specifying the name we show that the <code>puts</code>
method belongs to the <code>Kernel</code> module. 
</p>

<pre class="explanation">
puts self.class
</pre>

<p>
The line prints the <code>class</code> of the toplevel. We get the object type 
of the toplevel. It is the <code>Object</code>, which is 
the root of Ruby's class hierarchy.
</p>

<pre>
$ ./toplevel.rb
n1
n2
main
Object
</pre>

<p>
This is the output of the example. The n1, n2 are the local variables associated with
the toplevel. The main is the name given for the Ruby toplevel execution environment. 
Finally, the Object is the type of the toplevel. 
</p>

<hr class="btm">

<p>
We will have another example related to the Ruby toplevel. 
</p>

<pre class="code">
#!/usr/bin/ruby

@name = "Jane"
@age = 17

def info
   "#{@name} is #{@age} years old" 
end

puts self.instance_variables
puts self.private_methods.include? :info

puts info
</pre>

<p>
We show instance variables and methods that belong
to the toplevel environment. 
</p>

<pre class="explanation">
@name = "Jane"
@age = 17
</pre>

<p>
We define two instance variables. Instance variables begin with
the @ character in Ruby. Instance variables belong to a specific object
instance. In this case, they belong to the Ruby toplevel.
</p>

<pre class="explanation">
def info
   "#{@name} is #{@age} years old" 
end
</pre>

<p>
This is a method definition. Each method must belong to some object.
This method belongs to the toplevel object. All toplevel methods are private. 
Access to private methods is restricted. 
</p>

<pre class="explanation">
puts self.instance_variables
</pre>

<p>
The <code>instance_variables</code> method prints all instance
variables of the self, which points to the Ruby toplevel in this
context. 
</p>

<pre class="explanation">
puts self.private_methods.include? :info
</pre>

<p>
All toplevel methods are automatically private. The <code>private_methods</code>
returns all private methods of the object. Since there are many methods, we call
the <code>include?</code> method to check, if the info method is among them. 
Note that we refer to the info method by its symbolic name. 
</p>

<pre>
$ ./toplevel2.rb
@name
@age
true
Jane is 17 years old
</pre>

<p>
Example output. 
</p>

<p>
This chapter covered some basics of the objects in Ruby language.
</p>



<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified December 14, 2011 <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

